package com.wuage.infrastructure.utils;

/**
 * @author Shynin
 * @version 1.0
 * @date 9/27/21 8:42 PM
 */
import lombok.SneakyThrows;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Shynin
 * @version 1.0
 * @date 9/10/21 4:24 PM
 */
public class BeanUtils {
    private static final ModelMapper MODEL_MAPPER = new ModelMapper();

    static {
        // 使用严格模式匹配字段名称来转换
        MODEL_MAPPER.getConfiguration().setFullTypeMatchingRequired(true);
        MODEL_MAPPER.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
    }

    @SneakyThrows
    public static <T> T copyProperties(Object source, Class<T> clazz) {
        T target = clazz.newInstance();
        MODEL_MAPPER.map(source, target);
        return target;
    }

    public static void copyProperties(Object source, Object destination) {
        MODEL_MAPPER.map(source, destination);
    }

    public static <T> T copyProperties(Object source, Type destinationType) {
        return MODEL_MAPPER.map(source, destinationType);
    }

    public static <D, T> List<D> copyCollections(final Collection<T> entityList, Class<D> outClass) {
        if(entityList == null || entityList.size() == 0 ) {
            return new ArrayList<>();
        }
        return entityList.stream()
                .map(entity -> copyProperties(entity, outClass))
                .collect(Collectors.toList());
    }
}
